package com.zrf.base.knowledge.concurrent.demo;

import org.apache.commons.lang3.RandomUtils;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

/**
 * @date 2020/3/21
 * @AUTHER zhouruifeng
 */
public class CyclicBarrierDemo {
    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(2, ()-> System.out.println("success"));

        for (int i = 0; i < 2; i++) {
            new Thread(()-> {
                try {
                    TimeUnit.SECONDS.sleep(RandomUtils.nextInt(0,10));
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }finally {
                    try {
                        cyclicBarrier.await();
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    } catch (BrokenBarrierException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}
